<?php
namespace App\Repositories;

use App\Models\Permission;
use Illuminate\Support\Facades\Input;

class PermissionRepository
{
    /**
     * Get permissions list with parent info.
     *
     * @return collection
     */
    public function permissionsWithParent()
    {
        $start   = Input::get('start', 0);
        $length  = Input::get('length', 30);
        $page    = $start / $length + 1;
        
        $collection = Permission::with('parent')
            ->select('*')
            ->parent_id()
            ->display_name()
            ->name()
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->paginate($length, ['*'], 'page', $page);

        return $collection;
    }

    public function subPermissions($parent_id){
        $collection = Permission::select('*')
            ->parent_id($parent_id)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->get();

        return $collection;
    }

    public function permissions(){
        $collection = Permission::with('son')
            ->select(['id','display_name'])
            ->parent_id(0)
            ->get();
        return $collection;
    }

    public function store(array $input)
    {
        $model = Permission::create($input);

        if (empty($model->id)) {
            return false;
        }
        return true;
    }

    public function delete($permission, $id)
    {
        $permission->roles()->detach();
        return Permission::where('id', $id)->delete();
    }

    public function update(array $input, $permission)
    {
        $result = $permission->update($input);
        return $result;
    }
}